import React,{useEffect, useState, useRef} from 'react'
import {Modal,Tabs, Row, Col, Radio, Card, Input} from 'antd'
import CommonGraph from './ComonGraph'
import { useDrag, useDrop } from 'react-dnd'
import moment from 'moment'

const {TabPane} = Tabs
const {TextArea} = Input


const Node = ({warnInfo,uuid,exchangeIndex,index,trieIndex,id,options,femalUUID}) => {
  const ref = useRef(null)

  const [,drop] = useDrop({
    accept:`Node-${trieIndex}`,
    hover:(item, mointor) => {
      if(!ref.current){
        return
      }
      const dragIndex = item.index
      const hoverIndex = index
      if(dragIndex === hoverIndex){
        return
      }
      	// Determine rectangle on screen
			const hoverBoundingRect = ref.current && ref.current.getBoundingClientRect()

			// Get vertical middle
			const hoverMiddleY =
				(hoverBoundingRect.bottom - hoverBoundingRect.top) / 2

			// Determine mouse position
			const clientOffset = mointor.getClientOffset()

			// Get pixels to the top
			const hoverClientY = clientOffset.y - hoverBoundingRect.top

			// Only perform the move when the mouse has crossed half of the items height
			// When dragging downwards, only move when the cursor is below 50%
			// When dragging upwards, only move when the cursor is above 50%

			// Dragging downwards
			if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
				return
			}

			// Dragging upwards
			if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
				return
      }

      exchangeIndex(trieIndex,dragIndex, hoverIndex)

			item.index = hoverIndex

    }
  })

  const [{ isDragging }, drag] = useDrag({
		item: { type: `Node-${trieIndex}` , id, index },
		collect: (monitor) => ({
			isDragging: monitor.isDragging(),
		}),
	})

	const opacity = isDragging ? 0 : 1
  drag(drop(ref))
  const name = options.find(item => Number(item.id) === Number(id)).name


  return (
    <div ref={ref} style={{opacity:opacity}} className={`sel`}>
      {name}
    </div>

  )
}



const AlarmRadio = ({result,onClick}) => {
  const [checked, setChecked] = useState(result === 'C')
  const handleClick = () => {
    setChecked(preStatus => {
      onClick(!preStatus)
      return !preStatus
    })
  }
  return (
    <Radio checked={checked} onClick={handleClick}>
      已处理
    </Radio>
  )
}




export default ({popupVisible, onOk, onCancel, popupAlarms, chainName, castChains,collectorList, onTextAreaChange, onRadioClick}) => {

  const [visible,setVisible] = useState(false)
  useEffect(() => {
    let didCancel  = false
    if(didCancel){
      return
    }
    setVisible(popupVisible)
    return () => {
      didCancel = true
    };
  }, [popupVisible])
  const handleTextAreaChange = (id,e) =>{
    onTextAreaChange(id, e.target.value)
  }
  useEffect(() => {
    return () => {
      console.log('cancel')
    };
  }, [])
  const handleAlarmRadionClick = (id,checked) => {
    onRadioClick(id,checked)
  }
  // http://192.168.41.8/media?collector=190046e92db24189&start=1576416676102&duration=634089
  const handleCancel = () => {
    onCancel()
  }
  const handleOk = () => {
    onOk()
  }
  return (
    collectorList.length > 1 ? <Modal
    title={`链路名称：${chainName}`}
    destroyOnClose={true}
    visible={visible}
    onOk={handleOk}
    onCancel={handleCancel}
    style={{minWidth:'800px'}}
  >
    <Tabs type='card'>
      {
        popupAlarms.map(item => {
          const {c_name, id, cast_chain, type, occur_at, result, section_alarm, handle_remark} = item
          console.log('castChains.find(chain => chain.id === cast_chain)',castChains.find(chain => chain.id === cast_chain))
          const chain = castChains.find(chain => chain.id === cast_chain)
          let topo = chain ? chain.topo : '{}' //有可能存在链路配置被删除了，但是异常信息不存在了情况,所以这里需要做一个判定。
          const alarmType = type === 'D' ? '不匹配' : '系统故障'
          const alarmTime = moment(occur_at).format('YYYY-MM-DD HH:mm:ss')
          topo = JSON.parse(topo)

          const commonGraphProps = {
            Node,//Topo关系图的节点内部组件（类型为ReactComponent）
            topo:topo,//topo关系
            id,//链路的id
            chainName:chainName,//链路的名称
            hasButton:false,
            options:[{name:'请选择节点',id:0},...collectorList], //Selelt可选的option
            tierWidth:100,
            cavasHeight:200,
            marginTop:'0px'
          }

          return(
            <TabPane tab={c_name} key={id}>
              <Row type='flex' gutter={24} justify='space-between'>
                <Col span={14}>
                  <Row style={{display:'flex',alignContent:'center',padding:'20px'}}>
                      <CommonGraph {...commonGraphProps}> </CommonGraph>
                  </Row>
                  <Row style={{borderTop:'#ccc solid 1px',padding:'20px',display:'flex',flexDirection:'column',justifyContent:'space-between',lineHeight:'24px'}}>
                    <span style={{margin:'10px 0'}}>异常类型：{alarmType}</span>
                    <span style={{margin:'10px 0'}}>异常时间：{alarmTime}</span>
                    <span style={{margin:'10px 0'}}>处理结果：
                    <AlarmRadio result={result} onClick={(checked) => {handleAlarmRadionClick(id,checked)}}></AlarmRadio>
                    </span>
                    <span style={{display:'flex',justifyContent:'space-between'}}><span style={{textIndent:'2em'}}>备注：</span><span style={{flexGrow:'1'}}><TextArea defaultValue={handle_remark} onChange={(e) => handleTextAreaChange(id,e)} rows={5}></TextArea></span></span>
                  </Row>
                </Col>
                <Col span={10}>
                  {
                    section_alarm && section_alarm.map(item => {
                      const {p_name, id, type, alarm_at} = item
                      const alarmTime = moment(alarm_at).format('YYYY-MM-DD HH:mm:ss')
                      const alarmType = type === 'D' ? '不匹配' : '系统故障'
                      return (
                        <Card key={id} hoverable={true}>
                          <div style={{display:'flex',flexDirection:'column',justifyContent:'space-between',lineHeight:'16px'}}>
                            <span style={{margin:'5px 0'}}>节点名称: {p_name}</span>
                            <span style={{margin:'5px 0'}}>故障类型: {alarmType}</span>
                            <span style={{margin:'5px 0'}}>异常时间: {alarmTime}</span>
                          </div>
                        </Card>
                      )
                    })
                  }
                </Col>
              </Row>
            </TabPane>
          )
        })
      }
    </Tabs>
  </Modal> : ''
  )
}
